/*
 * EditProfile.java
 *
 * Created on February 25, 2007, 4:37 PM
 */

package d20chat;

import java.io.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.*;       // Used for JFileChooser
import java.awt.*;


/**
 * Allows a user to edit a selected profile in the profile manager.
 */
public class EditProfile extends javax.swing.JFrame {
    
    //public D20Chat tempMain;
    /**
     * Stores the current instance of profileManage (used to fetch variables).
     */
    public ProfileManager profileManager;
    
    private String username = "";
    private String name = "";
    private String email = "";
    private String phone = "";
    private String website = "";
    private String aboutMe = "";
    private boolean visible = false;
    
    
    /**
     * Creates new form PmEditProfile
     */
/**
     * Constructor for edit profile window.
     */
    public EditProfile() {
        initComponents();
        
        // Center Edit Profile jFrame
        Dimension scrn = getToolkit().getScreenSize();
        this.setBounds( (scrn.width-getWidth())/2, (scrn.height-getHeight())/2, getWidth(), getHeight() );
    }
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
/**
     * 
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        lblUsername = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        lblName = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        lblEmail = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        lblPhone = new javax.swing.JLabel();
        txtPhone = new javax.swing.JTextField();
        lblWebsite = new javax.swing.JLabel();
        txtWebsite = new javax.swing.JTextField();
        lblAboutMe = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtAboutMe = new javax.swing.JTextArea();
        chkVisible = new javax.swing.JCheckBox();
        save = new javax.swing.JButton();
        cancel = new javax.swing.JButton();

        setTitle("Edit Profile");
        setLocationByPlatform(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        lblUsername.setForeground(java.awt.Color.darkGray);
        lblUsername.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblUsername.setText("Username:");

        lblName.setForeground(java.awt.Color.darkGray);
        lblName.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblName.setText("Name:");

        lblEmail.setForeground(java.awt.Color.darkGray);
        lblEmail.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblEmail.setText("Email:");

        lblPhone.setForeground(java.awt.Color.darkGray);
        lblPhone.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblPhone.setText("Phone:");

        lblWebsite.setForeground(java.awt.Color.darkGray);
        lblWebsite.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblWebsite.setText("Website:");

        lblAboutMe.setForeground(java.awt.Color.darkGray);
        lblAboutMe.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblAboutMe.setText("About Me:");

        txtAboutMe.setColumns(20);
        txtAboutMe.setLineWrap(true);
        txtAboutMe.setRows(5);
        txtAboutMe.setWrapStyleWord(true);
        jScrollPane1.setViewportView(txtAboutMe);

        chkVisible.setForeground(java.awt.Color.darkGray);
        chkVisible.setText("Make my profile visible to others");
        chkVisible.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        chkVisible.setMargin(new java.awt.Insets(0, 0, 0, 0));

        save.setText("Save");
        save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblAboutMe)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblWebsite)
                            .addComponent(lblPhone)
                            .addComponent(lblEmail)
                            .addComponent(lblUsername)
                            .addComponent(lblName))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtWebsite, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
                                    .addComponent(txtEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
                                    .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtName, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                    .addComponent(chkVisible)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(save)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 178, Short.MAX_VALUE)
                        .addComponent(cancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblUsername)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblEmail))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPhone)
                    .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtWebsite, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblWebsite))
                .addGap(16, 16, 16)
                .addComponent(lblAboutMe)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(15, 15, 15)
                .addComponent(chkVisible)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(save)
                    .addComponent(cancel))
                .addContainerGap())
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    
/********************************************************************************
  Method: formWindowOpened
  Description: Form window opened event for edit profile window
  Parameters: evt
  Used by: EditProfile.java
  Uses: NONE
********************************************************************************/
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // Get selected profile username
        String selectedProfile = profileManager.getSelectedProfile();
        
        // Build profile path
        String filePath = profileManager.profileDir + selectedProfile + ".txt";
        
        // Read profile from file
        String strVisible = "";
        try {
            // Create a buffer for our file to read into
            BufferedReader bin = new BufferedReader(new FileReader(filePath));
            
            // Read in profile
            username = bin.readLine();
            name = bin.readLine();
            email = bin.readLine();
            phone = bin.readLine();
            website = bin.readLine();
            aboutMe = bin.readLine();
            strVisible = bin.readLine();

            bin.close();
        }
        catch (Exception e)
        {
                System.err.println ("Error reading file");
        }
        
        if (strVisible.compareTo("true") == 0)
            visible = true;
        else
            visible = false;

        // Set form profile information to selected profile
        txtUsername.setText(username);
        txtName.setText(name);
        txtEmail.setText(email);
        txtPhone.setText(phone);
        txtWebsite.setText(website);
        txtAboutMe.setText(aboutMe);
        chkVisible.setSelected(visible);
    }//GEN-LAST:event_formWindowOpened

    
/********************************************************************************
  Method: saveActionPerformed
  Description: Save button action performed for the edit profile window
  Parameters: evt
  Used by: ProfileManager.java
  Uses: removeProfile, addProfile, writeProfile
********************************************************************************/
    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
        // Save all profile information
        String newUsername = this.txtUsername.getText();
        name = this.txtName.getText();
        email = this.txtEmail.getText();
        phone = this.txtPhone.getText();
        website = this.txtWebsite.getText();
        aboutMe = this.txtAboutMe.getText();
        visible = this.chkVisible.isSelected();
        
        // If username has been changed then delete old file
        // Otherwise, don't worry about saving username, it's already stored
        //  (since username wasn't changed)
        if (!(newUsername.compareTo(username) == 0)) {
            // Ask user if they're sure they want to overwrite the profile
            String message = "Profile " + newUsername + " already exists.\n";
            message = message + "Do you want to overwrite it with the new info?";
            
            int result = JOptionPane.showOptionDialog(null, message, "Edit Profile", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null);
            
            if (result == JOptionPane.YES_OPTION) {
                // User decided to overwrite profile with newly edited profile,
                //  so add it to the jList and write profile to file
                profileManager.removeProfile(username);
                profileManager.addProfile(newUsername);
                this.writeProfile(newUsername);
                username = newUsername;
                // ** MUST BE IN THIS ORDER **
            
                // Done with saving profile to file, hide window
                this.setVisible(false);
            }
        } else {
            // Write profile to file
            this.writeProfile(username);

            // Done with saving profile to file, hide window
            this.setVisible(false);
        }
            
    }//GEN-LAST:event_saveActionPerformed

    
/********************************************************************************
  Method: writeProfile
  Description: Write method for writing a profile to file
  Parameters: newUsername
  Used by: saveActionMethod
  Uses: addProfile
********************************************************************************/
    private void writeProfile(String newUsername) {
        // Save the profile to file
        String saveLocation = profileManager.profileDir + newUsername + ".txt";

        FileOutputStream out; // declare a file output object
        PrintStream p; // declare a print stream object

        try {
            // Create a new file output stream
            //  connected to "saveLocation" path
            out = new FileOutputStream(saveLocation);

            // Connect print stream to the output stream
            p = new PrintStream(out);

            // Write profile information to file
            p.println (newUsername);
            p.println (name);
            p.println (email);
            p.println (phone);
            p.println (website);
            p.println (aboutMe);
            p.println (visible);

            p.close();

            // Add new profile to profileList in Profile Manager
            if (username.compareTo(newUsername) == 0) {
                profileManager.addProfile(newUsername);
            }
        }
        catch (Exception e)
        {
            System.err.println (e.getMessage());
        }
    }
    
    
/********************************************************************************
  Method: cancelActionPerformed
  Description: Cancel button action for edit profile window
  Parameters: evt
  Used by: EditProfile.java
  Uses: NONE
********************************************************************************/
    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        // Hide form
        this.setVisible(false);
    }//GEN-LAST:event_cancelActionPerformed
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JCheckBox chkVisible;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAboutMe;
    private javax.swing.JLabel lblEmail;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblPhone;
    private javax.swing.JLabel lblUsername;
    private javax.swing.JLabel lblWebsite;
    private javax.swing.JButton save;
    private javax.swing.JTextArea txtAboutMe;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtPhone;
    private javax.swing.JTextField txtUsername;
    private javax.swing.JTextField txtWebsite;
    // End of variables declaration//GEN-END:variables
    
}
